<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>考评员-考生自动匹配系统</title>
  <!-- 引入Tailwind CSS -->
  <script src="./public/a.js"></script>
  <!-- 引入Font Awesome图标 -->
  <link href="./public/b.css" rel="stylesheet">
  
  <!-- 自定义Tailwind配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3b82f6',
            secondary: '#10b981',
            accent: '#8b5cf6',
            dark: '#1e293b',
            light: '#f8fafc'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
      }
      .input-focus {
        @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
      }
      .btn-hover {
        @apply hover:shadow-lg transform hover:-translate-y-0.5 transition-all duration-300;
      }
      .text-balance {
        text-wrap: balance;
      }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen font-sans text-dark">
  <!-- 顶部导航 -->
  <header class="bg-white shadow-md sticky top-0 z-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex justify-between h-16">
        <div class="flex items-center">
          <div class="flex-shrink-0 flex items-center">
            <i class="fa fa-random text-2xl text-primary mr-2"></i>
            <span class="text-xl font-bold text-dark">考评员-考生自动匹配系统</span>
          </div>
        </div>
        <div class="flex items-center">
          <button id="helpBtn" class="text-gray-600 hover:text-primary px-3 py-2 rounded-md text-sm font-medium btn-hover">
            <i class="fa fa-question-circle mr-1"></i> 帮助
          </button>
        </div>
      </div>
    </div>
  </header>

  <!-- 主要内容区 -->
  <main class="max-w-4xl mx-auto px-4 py-8 sm:px-6 lg:px-8">
    <!-- 欢迎信息卡片 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-8 card-shadow">
      <div class="flex flex-col md:flex-row items-center justify-between">
        <div class="mb-4 md:mb-0">
          <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark mb-2">欢迎使用智能匹配系统</h1>
          <p class="text-gray-600 text-balance">快速上传Excel文件，系统将自动完成考评员与考生的匹配工作</p>
        </div>
        <div class="flex space-x-3">
          <button id="guideBtn" class="bg-blue-50 text-primary px-4 py-2 rounded-lg border border-blue-200 flex items-center btn-hover">
            <i class="fa fa-book mr-2"></i>使用指南
          </button>
        </div>
      </div>
    </div>

    <!-- 主要功能区 -->
    <div class="grid grid-cols-1 gap-8">
      <!-- 输入表单卡片 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden card-shadow">
        <div class="p-6">
          <h2 class="text-xl font-semibold mb-6 text-dark border-b pb-3">
            <i class="fa fa-cogs text-primary mr-2"></i>参数设置
          </h2>
          
          <div class="space-y-6">
            <!-- 复制功能快捷区 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
              <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 cursor-pointer hover:shadow-md transition-all duration-300" onClick="copy('=INT((ROW(A1)-1)/平均个数(向上取整))+1')">
                <div class="flex items-center justify-between">
                  <div>
                    <div class="font-medium text-dark">Excel平均计算函数</div>
                    <div class="text-sm text-gray-500 mt-1">点击复制实用公式</div>
                  </div>
                  <div class="bg-white p-2 rounded-full shadow-sm">
                    <i class="fa fa-copy text-primary"></i>
                  </div>
                </div>
              </div>
              <div class="bg-gradient-to-r from-green-50 to-teal-50 rounded-lg p-4 cursor-pointer hover:shadow-md transition-all duration-300" id="approximateCalcCard">
                <div class="flex items-center justify-between">
                  <div>
                    <div class="font-medium text-dark">近似计算</div>
                    <div class="text-sm text-gray-500 mt-1">自定义参数计算分配方案</div>
                  </div>
                  <div class="bg-white p-2 rounded-full shadow-sm">
                    <i class="fa fa-calculator text-secondary"></i>
                  </div>
                </div>
              </div>
            </div>

            <!-- 输入字段 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="space-y-2">
                <label for="subjectId" class="block text-sm font-medium text-gray-700">科目ID <span class="text-red-500">*</span></label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-hashtag text-gray-400"></i>
                  </div>
                  <input 
                    type="number" 
                    id="subjectId" 
                    placeholder="请输入科目ID，如：1289" 
                    min="1" 
                    value="1289" 
                    class="block w-full pl-10 pr-3 py-3 bg-gray-50 border border-gray-300 rounded-lg input-focus transition-all duration-200"
                    required
                  />
                </div>
              </div>
              <div class="space-y-2">
                <label for="password" class="block text-sm font-medium text-gray-700">密码 <span class="text-red-500">*</span></label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-lock text-gray-400"></i>
                  </div>
                  <input 
                    type="text" 
                    id="password" 
                    placeholder="请输入密码" 
                    class="block w-full pl-10 pr-3 py-3 bg-gray-50 border border-gray-300 rounded-lg input-focus transition-all duration-200"
                    required
                  />
                </div>
              </div>
            </div>

            <!-- 文件上传区域 -->
            <div class="space-y-2">
              <label for="excelFile" class="block text-sm font-medium text-gray-700">上传Excel文件 <span class="text-red-500">*</span></label>
              <div id="dropArea" class="mt-1 border-2 border-dashed border-gray-300 rounded-xl p-8 text-center bg-white hover:border-primary transition-all duration-300">
                <div class="flex flex-col items-center">
                  <div class="bg-blue-50 rounded-full p-4 mb-4">
                    <i class="fa fa-file-excel-o text-3xl text-primary"></i>
                  </div>
                  <div class="space-y-2">
                    <p class="text-lg font-medium text-gray-900">拖放Excel文件到此处，或</p>
                    <label for="excelFile" class="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-primary hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary btn-hover cursor-pointer">
                      <i class="fa fa-upload mr-2"></i>选择文件
                    </label>
                    <p class="text-sm text-gray-500">支持 .xls 和 .xlsx 格式文件，最大10MB</p>
                  </div>
                  <!-- 上传文件信息显示 -->
                  <div id="fileInfo" class="mt-6 hidden w-full">
                    <div class="bg-gray-50 rounded-lg p-4 flex items-center">
                      <i class="fa fa-check-circle text-green-500 text-xl mr-3"></i>
                      <div class="flex-grow overflow-hidden">
                        <div id="fileName" class="font-medium text-gray-900 truncate"></div>
                        <div id="fileSize" class="text-sm text-gray-500"></div>
                      </div>
                      <button id="removeFile" class="text-gray-400 hover:text-red-500 transition-colors">
                        <i class="fa fa-times text-lg"></i>
                      </button>
                    </div>
                  </div>
                </div>
                <input id="excelFile" name="excelFile" type="file" accept=".xls, .xlsx" class="sr-only">
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex justify-center pt-4">
              <button 
                id="processBtn" 
                disabled 
                class="inline-flex items-center px-8 py-3.5 border border-transparent text-base font-medium rounded-lg shadow-md text-white bg-primary hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed btn-hover"
              >
                <span id="btnText">🚀 开始处理</span>
                <svg id="btnLoader" class="animate-spin -ml-1 mr-2 h-5 w-5 text-white hidden" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 结果显示区域 -->
      <div class="bg-white rounded-xl shadow-sm overflow-hidden card-shadow">
        <div class="p-6">
          <h2 class="text-xl font-semibold mb-4 text-dark border-b pb-3">
            <i class="fa fa-table text-primary mr-2"></i>处理结果
          </h2>
          <div id="result" class="min-h-[200px] bg-gray-50 rounded-lg p-8 flex items-center justify-center border border-gray-200">
            <div class="text-center">
              <i class="fa fa-file-text-o text-5xl text-gray-300 mb-4"></i>
              <p class="text-gray-500">上传文件并点击"开始处理"按钮后，结果将显示在这里</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 mt-12">
    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
      <p class="text-center text-gray-500 text-sm">
        © 2023 考评员-考生自动匹配系统 | 版本 1.0.0
      </p>
    </div>
  </footer>

  <!-- 帮助模态框 -->
  <div id="helpModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h3 class="text-xl font-bold text-dark">使用帮助</h3>
          <button id="closeHelpModal" class="text-gray-400 hover:text-gray-500">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      <div class="p-6 space-y-4">
        <div>
          <h4 class="font-semibold text-dark mb-2">1. 系统功能</h4>
          <p class="text-gray-600">本系统用于自动匹配考评员与考生，简化考试安排流程。</p>
        </div>
        <div>
          <h4 class="font-semibold text-dark mb-2">2. 使用步骤</h4>
          <ol class="list-decimal list-inside text-gray-600 space-y-1">
            <li>输入科目ID和密码</li>
            <li>上传包含考评员和考生信息的Excel文件</li>
            <li>点击"开始处理"按钮</li>
            <li>等待系统处理完成，查看匹配结果</li>
          </ol>
        </div>
        <div>
          <h4 class="font-semibold text-dark mb-2">3. 注意事项</h4>
          <ul class="list-disc list-inside text-gray-600 space-y-1">
            <li>确保Excel文件格式正确，符合系统要求</li>
            <li>文件大小不能超过10MB</li>
            <li>处理过程中请勿关闭页面</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- 参数输入模态框 -->
  <div id="paramsModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h3 class="text-xl font-bold text-dark">近似计算参数设置</h3>
          <button id="closeParamsModal" class="text-gray-400 hover:text-gray-500">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      <div class="p-6 space-y-5">
        <div>
          <label for="totalCandidates" class="block text-sm font-medium text-gray-700 mb-1">考生总数</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-users text-gray-400"></i>
            </div>
            <input 
              type="number" 
              id="totalCandidates" 
              value="389" 
              min="1" 
              class="block w-full pl-10 pr-3 py-3 bg-gray-50 border border-gray-300 rounded-lg input-focus transition-all duration-200"
              required
            />
          </div>
          <p class="mt-1 text-xs text-gray-500">输入需要分配的考生总人数</p>
        </div>
        <div>
          <label for="totalExaminers" class="block text-sm font-medium text-gray-700 mb-1">考评员数量</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-user-circle text-gray-400"></i>
            </div>
            <input 
              type="number" 
              id="totalExaminers" 
              value="6" 
              min="1" 
              class="block w-full pl-10 pr-3 py-3 bg-gray-50 border border-gray-300 rounded-lg input-focus transition-all duration-200"
              required
            />
          </div>
          <p class="mt-1 text-xs text-gray-500">输入参与分配的考评员数量</p>
        </div>
        <div class="pt-2 flex justify-end space-x-3">
          <button id="closeParamsModal" class="px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all">
            取消
          </button>
          <button id="calculateParamsBtn" class="px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-secondary hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-secondary transition-all">
            <i class="fa fa-calculator mr-1"></i> 计算并复制
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 引入脚本 -->
  <script src="renderer.js"></script>
  <script src="./Algorithm/index.js"></script>
  
  <!-- 交互逻辑 -->
  <script>
    // DOM元素引用
    const excelFileInput = document.getElementById('excelFile');
    // const processBtn = document.getElementById('processBtn');
    const dropArea = document.getElementById('dropArea');
    const fileInfo = document.getElementById('fileInfo');
    const fileName = document.getElementById('fileName');
    const fileSize = document.getElementById('fileSize');
    const removeFileBtn = document.getElementById('removeFile');
    const helpBtn = document.getElementById('helpBtn');
    const helpModal = document.getElementById('helpModal');
    const closeHelpModalBtn = document.getElementById('closeHelpModal');
    const btnText = document.getElementById('btnText');
    const btnLoader = document.getElementById('btnLoader');
    const guideBtn = document.getElementById('guideBtn');

    // 复制文本到剪贴板的函数
    function copy(text) {
      // 现代浏览器使用Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text)
          .then(() => {
            showNotification('复制成功！', 'success');
          })
          .catch(err => {
            console.error('复制失败:', err);
            fallbackCopyTextToClipboard(text);
          });
      } else {
        // 降级方案，兼容旧浏览器
        fallbackCopyTextToClipboard(text);
      }
    }

    // 降级复制方案
    function fallbackCopyTextToClipboard(text) {
      try {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        const successful = document.execCommand('copy');
        if (successful) {
          showNotification('复制成功！', 'success');
        } else {
          showNotification('复制失败，请手动复制', 'error');
        }
        
        document.body.removeChild(textArea);
      } catch (err) {
        console.error('复制失败:', err);
        showNotification('复制失败，请手动复制', 'error');
      }
    }

    // 近似计算函数
    function vcopy() {
      // 显示参数输入模态框
      document.getElementById('paramsModal').classList.remove('hidden');
    }

    // 文件选择处理
    excelFileInput.addEventListener('change', handleFileSelect);

    function handleFileSelect(e) {
      if (e.target.files && e.target.files.length > 0) {
        const file = e.target.files[0];
        
        // 检查文件类型
        if (!file.name.endsWith('.xls') && !file.name.endsWith('.xlsx')) {
          showNotification('请上传Excel格式的文件 (.xls 或 .xlsx)', 'error');
          resetFileInput();
          return;
        }
        
        // 检查文件大小 (10MB)
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
          showNotification('文件大小不能超过10MB', 'error');
          resetFileInput();
          return;
        }
        
        // 显示文件信息
        fileName.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
        fileInfo.classList.remove('hidden');
        
        // 启用处理按钮
        processBtn.disabled = false;
        
        // 添加文件选择的视觉反馈
        dropArea.classList.add('border-green-500', 'bg-green-50');
        setTimeout(() => {
          dropArea.classList.remove('bg-green-50');
        }, 800);
        
        // 将结果区域重置为准备状态
        document.getElementById('result').innerHTML = `
          <div class="text-center">
            <i class="fa fa-hourglass-half text-5xl text-primary mb-4"></i>
            <p class="text-gray-600">文件已上传，点击"开始处理"按钮开始匹配</p>
          </div>
        `;
      } else {
        resetFileInput();
      }
    }

    // 重置文件输入
    function resetFileInput() {
      excelFileInput.value = '';
      fileInfo.classList.add('hidden');
      processBtn.disabled = true;
      dropArea.classList.remove('border-green-500', 'bg-green-50');
    }

    // 移除文件按钮
    removeFileBtn.addEventListener('click', resetFileInput);

    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
      e.preventDefault();
      e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
      dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
      dropArea.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
      dropArea.classList.add('border-primary', 'bg-blue-50');
    }

    function unhighlight() {
      dropArea.classList.remove('border-primary', 'bg-blue-50');
    }

    dropArea.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
      const dt = e.dataTransfer;
      const files = dt.files;
      
      if (files.length > 0) {
        excelFileInput.files = files;
        // 触发change事件以更新UI
        const event = new Event('change');
        excelFileInput.dispatchEvent(event);
      }
    }

    // 处理按钮点击事件
    processBtn.addEventListener('click', function() {
      if (!this.disabled) {
        // 显示加载状态
        btnText.textContent = '处理中...';
        btnLoader.classList.remove('hidden');
        this.disabled = true;
        
        // 在实际应用中，这里会调用处理函数
        // 模拟处理过程
        setTimeout(() => {
          // 恢复按钮状态
          btnText.textContent = '🚀 开始处理';
          btnLoader.classList.add('hidden');
          this.disabled = false;
          
          // 在实际应用中，这里会显示处理结果
          // 这里只是模拟，实际结果应该由renderer.js或Algorithm/index.js处理
        }, 2000);
      }
    });

    // 格式化文件大小
    function formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 显示通知
    function showNotification(message, type = 'info') {
      // 创建通知元素
      const notification = document.createElement('div');
      
      // 设置样式基于类型
      let bgColor, textColor, icon;
      switch (type) {
        case 'success':
          bgColor = 'bg-green-500';
          textColor = 'text-white';
          icon = 'fa-check-circle';
          break;
        case 'error':
          bgColor = 'bg-red-500';
          textColor = 'text-white';
          icon = 'fa-exclamation-circle';
          break;
        case 'warning':
          bgColor = 'bg-yellow-500';
          textColor = 'text-white';
          icon = 'fa-exclamation-triangle';
          break;
        default:
          bgColor = 'bg-blue-500';
          textColor = 'text-white';
          icon = 'fa-info-circle';
      }
      
      // 设置通知样式和内容
      notification.className = `fixed bottom-4 right-4 ${bgColor} ${textColor} px-4 py-3 rounded-lg shadow-lg z-50 flex items-center transform transition-all duration-500 translate-y-10 opacity-0`;
      notification.innerHTML = `
        <i class="fa ${icon} mr-2"></i>
        <span>${message}</span>
      `;
      
      // 添加到文档
      document.body.appendChild(notification);
      
      // 显示通知
      setTimeout(() => {
        notification.classList.remove('translate-y-10', 'opacity-0');
      }, 100);
      
      // 自动隐藏通知
      setTimeout(() => {
        notification.classList.add('translate-y-10', 'opacity-0');
        setTimeout(() => {
          document.body.removeChild(notification);
        }, 500);
      }, 3000);
    }

    // 帮助模态框
    helpBtn.addEventListener('click', () => {
      helpModal.classList.remove('hidden');
    });
    
    closeHelpModalBtn.addEventListener('click', () => {
      helpModal.classList.add('hidden');
    });
    
    helpModal.addEventListener('click', (e) => {
      if (e.target === helpModal) {
        helpModal.classList.add('hidden');
      }
    });
    
    guideBtn.addEventListener('click', () => {
      helpModal.classList.remove('hidden');
    });
    
    // 按ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        if (!helpModal.classList.contains('hidden')) {
          helpModal.classList.add('hidden');
        }
        if (!paramsModal.classList.contains('hidden')) {
          paramsModal.classList.add('hidden');
        }
      }
    });
    
    // 参数输入模态框事件
    document.getElementById('approximateCalcCard').addEventListener('click', () => {
      paramsModal.classList.remove('hidden');
    });
    
    document.getElementById('closeParamsModal').addEventListener('click', () => {
      paramsModal.classList.add('hidden');
    });
    
    document.getElementById('paramsModal').addEventListener('click', (e) => {
      if (e.target === document.getElementById('paramsModal')) {
        paramsModal.classList.add('hidden');
      }
    });
    
    document.getElementById('calculateParamsBtn').addEventListener('click', () => {
      const totalCandidates = parseInt(document.getElementById('totalCandidates').value);
      const totalExaminers = parseInt(document.getElementById('totalExaminers').value);
      
      if (isNaN(totalCandidates) || totalCandidates <= 0 || isNaN(totalExaminers) || totalExaminers <= 0) {
        showNotification('请输入有效的正整数参数', 'error');
        return;
      }
      
      try {
        let res = distributeApproximately(totalCandidates, totalExaminers);
        copy(res);
        paramsModal.classList.add('hidden');
        showNotification('计算结果已复制到剪贴板', 'success');
      } catch (error) {
        console.error('计算失败:', error);
        showNotification('计算失败，请重试', 'error');
      }
    });
  </script>
</body>
</html>